package net.xinqushi.design.interceptor.demo;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author xjie
 * @description 拦截器主程序
 */
public class Main {

    //请求资金方接口
    public static void main(String[] args) throws IOException {
        Channel channel = new Channel();
        Request req = new Request();
        //set msg ....
        req.setInterfaceId("interfaceId1");
        req.setRequestSeqNo("随机SeqNo数字");
        req.setBankCode("CLX");
        req.setCorporateCode("XXYP");
        req.setProductType("1");
        req.setUserId(123456);
        req.setOrderCode("3451654161651565");

        Queue<Interceptor> interceptors = new LinkedList<Interceptor>(); // 拦截器列表

        // 日志拦截器,功能: 打印日志
        Interceptor logInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                System.out.println("userId: " + chain.request().getUserId()); // 请求接口的用户ID
                System.out.println("orderCode: " + chain.request().getOrderCode());//请求接口的orderCode
                System.out.println("InterfaceId " + chain.request().getInterfaceId());//请求接口的接口Id
                return chain.proceed(chain.request());
            }
        };
        // 加密拦截器,功能: 加密 、 加签名
        Interceptor jjmInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                // 获取加密后的infoContent
                String infoContent = "";
                String infoSign = "";
                chain.request().setInfoContent(infoContent);
                chain.request().setInfoSign(infoSign);
                return chain.proceed(chain.request());
            }
        };
        // 请求接口拦截器 功能: 请求资金方接口并返回
        Interceptor requestInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                return channel.post(chain.request());
            }
        };

        interceptors.add(logInterceptor);
        interceptors.add(jjmInterceptor);
        interceptors.add(requestInterceptor);
        Chain realChain = new ConcreteChain(interceptors,req);

        Response res = realChain.proceed(req);
        System.out.println("返回结果 : " + JSON.toJSONString(res));
    }
}
